#!/bin/bash
# Program:
#  This program shows
# History:
# 2017-05-19 zmqc First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# 支持 vmware
################################
# 变量定义区
################################

existvms=$(vmrun list|grep centos)

################################
# 函数定义区
################################
# 开机
function boot() {
    if [ -z ${existvms} ]; then
        echo "boot..."
        vmrun start "/home/zmqc/backups/vmware/centos/centos.vmx" nogui
        while [ -z ${existvms} ]
        do
            sleep 1
            existvms=$(vmrun list|grep centos)
        done
    fi

}

# 远程链接
function connect() {
    echo "connect..."
    ssh 192.168.56.128
}


# 测试是否可以连接
function testip() {
    if [ -z ${existvms} ]; then
        echo "虚拟机未启动"
        exit 0
    fi

    result="1"
    while [ "${result}" != "0" ]
    do
        ping -c 1 -w 1 192.168.56.128 &> /dev/null && result=0 || result=1
        sleep 0.3
    done
    success="虚拟机已经启动"
}

# 帮助信息
function help() {
    echo -e "\
     help     ( 查看 centosvm 的参数介绍 )\n\
     ls       ( 查看有哪些虚拟机 ) \n\
     boot     ( 启动虚拟机 )\n\
     ssh      ( 用ssh进行远程连接 )\n\
     ping     ( ping 一下虚拟机的网络 )\n\
     ss       ( savestate 保存状态然后关闭 )\n\
     shutdown ( 关机 )\n\
     poweroff ( 强制关机 )"
}


################################
# 主程序区
################################
# 不带任何参数则直接启动
if [ $# == 0 ]; then
    boot
    testip
    connect
    exit
elif [ $# != 1 ]; then
    echo  "     本程序不接受参数或者只接收一个参数, 参数列表如下："
    help
    exit
fi


# 针对不同参数进行处理
case $1 in
    "help")
        help
        ;;
    "ls")
        vmrun list
        ;;
    "boot")
        boot
        ;;
    "ssh")
        connect
        ;;
    "ping")
        ping -c 1 -w 1 192.168.56.128
        ;;
    "ss")
        vmrun suspend "/home/zmqc/backups/vmware/centos/centos.vmx"
        ;;
    "shutdown")
        vmrun stop "/home/zmqc/backups/vmware/centos/centos.vmx" soft
        ;;
    "poweroff")
        vmrun stop "/home/zmqc/backups/vmware/centos/centos.vmx" hard
        ;;
    *)
        echo "     参数错误"
        echo "     本程序不接受参数或者只接收一个参数, 参数列表如下："
        help
        ;;
esac
